package com.objects;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Vector;

import com.data.LineData;
import com.data.Point3D;
import com.editors.TrackEditor;

public class Track {
	
	
	public Track() {
		
	}

	public Track(Point3D start, Point3D end) {
		super();
		this.start = start;
		this.end = end;
		
		initialize();
	}


	public double length;
	public double orientation;
	public Point3D start;
	public Point3D end;

	public static int STATUS_STRAIGHT=0;
	public static int STATUS_DEVIATION=1;

	int status=STATUS_STRAIGHT;



	public void initialize() {

		orientation=calculateOrientation(start,end);
		length=Point3D.distance(start,end);
	}

	public static double calculateOrientation(Point3D start, Point3D end) {
		double teta=0;
		Point3D relativePosition=end.substract(start);
		Point3D axis=new Point3D(1,0,0);

		double cosTeta=relativePosition.x/
				(Point3D.calculateNorm(relativePosition));

		double crossProductZ=relativePosition.y;

		teta=Math.acos(cosTeta);
		if(crossProductZ<0)
			teta=2*Math.PI-teta;
		//System.out.println(teta);
		return teta;
	}


	public static Track[] loadRailFromFile(File file) {

		Track[] tracks=null;
		

		try {

			//read points

			Vector points=new Vector();
			Vector lines=new Vector();
			
			Vector allTracks=new Vector();
			
			boolean isTrack=false;

			BufferedReader br=new BufferedReader(new FileReader(file));

			String str=null;
			int rows=0;
			while((str=br.readLine())!=null){
				
				if(str.equals("<track>"))
					isTrack=true;
				else if(str.equals("</track>"))
					isTrack=false;
				
				if(isTrack){
					
					
					if(str.indexOf("P")>=0){
						points.add(TrackEditor.composePoint(str));
					}
					rows++;	
					
				}

		

			}

			br.close();
			
			isTrack=false;
			
			br=new BufferedReader(new FileReader(file));

			str=null;
			rows=0;
			
			while((str=br.readLine())!=null){
				
				if(str.equals("<track>"))
					isTrack=true;
				else if(str.equals("</track>"))
					isTrack=false;

				if(isTrack){
					
					if(str.indexOf("L")>=0){
						LineData ld=TrackEditor.composeLineData(str);

						int startIndex=ld.getIndex(0);
						int endIndex=ld.getIndex(1);

						Point3D start=(Point3D) points.elementAt(startIndex);
						Point3D end=(Point3D) points.elementAt(endIndex);

						lines.add(ld);
						
						Track track=new Track(start,end);
						
						allTracks.add(track);
						
					}

				}

			}
			br.close();
			
			tracks=new Track[allTracks.size()];
			
			for (int i = 0; i < allTracks.size(); i++) {
				tracks[i] = (Track) allTracks.elementAt(i);
			}
			
		} catch (Exception e) {

			e.printStackTrace();
		}
		
		
		return tracks;

	}		

}
